/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.urlhandling;

import org.gidoo.cms.view.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.wicket.IRequestTarget;
import org.apache.wicket.Page;
import org.apache.wicket.request.RequestParameters;
import org.apache.wicket.request.target.coding.IRequestTargetUrlCodingStrategy;
import org.apache.wicket.request.target.component.PageRequestTarget;


/**
 * This class is used to forward every standard-request to the rendering page.
 *
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class UrlCodingStrategy implements IRequestTargetUrlCodingStrategy
{

  private Class pageClass;
  private String mountPath;

  /**
   * Creates a new instance of UrlCodingStrategy.
   *
   * @param pageClass The class you want to use for rendering the CMS-content.
   * @param mountPath The path were the application is mounted to. No leading slash, please!
   */
  public UrlCodingStrategy(Class pageClass, String mountPath)
  {
    this.pageClass = pageClass;
    this.mountPath = mountPath;
  }
  
  @Override
  public IRequestTarget decode(RequestParameters requestParameters)
  {
    try
    {
      return new PageRequestTarget((Page) pageClass.newInstance());
    } catch (Exception ex)
    {
      Logger.getLogger(UrlCodingStrategy.class.getName()).log(Level.SEVERE, null, ex);
      // fallback
      return new PageRequestTarget(new ContentView());
    }
  }
  
  @Override
  public CharSequence encode(IRequestTarget requestTarget)
  {
    return new String("");
  }
  
  @Override
  public boolean matches(IRequestTarget requestTarget)
  {
    return false;
  }
  
  @Override  
  public boolean matches(String path, boolean caseSensitive)
  {
    if(caseSensitive)
    {
      return path.startsWith(mountPath);
    }
    else
    {
      return path.toLowerCase().startsWith(mountPath.toLowerCase());
    }
  }
  
  @Override
  public String getMountPath()
  {
    return mountPath;
  }


}